package org.javaforever.cookieshop.serviceimpl;

import java.util.List;
import org.javaforever.cookieshop.dao.PermissionDao;
import org.javaforever.cookieshop.domain.PermissionBean;
import org.javaforever.cookieshop.service.PermissionService;
import org.javaforever.cookieshop.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

@Service
public class PermissionServiceImpl implements PermissionService{
	@Autowired
	protected PermissionDao dao;

	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public void activateAllPermissions(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.activatePermission(id);
        }
	}

	@Override
	public Boolean activatePermission(Long id) throws Exception{
        dao.activatePermission(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean addPermission(PermissionBean permission) throws Exception{
        dao.saveAndFlush(permission);
        return true;
	}

	@Override
	public void cloneAllPermissions(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            clonePermission(id);
        }
	}

	@Override
	public Boolean clonePermission(Long id) throws Exception{
        PermissionBean permission = dao.findPermissionFullInfoById(id);
        
        String permName = permission.getPermName();
        String shortName = permName;
        if (permName.contains("_") && StringUtil.isInteger(permName.substring(permName.lastIndexOf('_')+1,permName.length()))) {
            shortName = permName.substring(0,permName.lastIndexOf('_'));
        }
        List<PermissionBean> names = dao.searchPermissionIndexedNamesByShortName(shortName);
        int indexNum = 1;
        for (PermissionBean permission0:names) {
            String _name = permission0.getPermName();
            if (_name.contains("_") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {
                int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));
                if (index >= indexNum) {
                    indexNum = index + 1;
                }
            }
        }
        String indexName = shortName + "_" + indexNum;
        PermissionBean permission1 = permission.clone();
        permission1.setId(null);
        permission1.setPermName(indexName);
        addPermission(permission1);
        return true;
	}

	@Override
	public Integer countActivePermissionRecords() throws Exception{
        return dao.countActivePermissionRecords();
	}

	@Override
	public Integer countSearchPermissionsByFieldsRecords(PermissionBean permission) throws Exception{
        String jpql = "select count(*) as countNum from PermissionBean p where 1=1 ";
        if (permission.getPermName() != null) {
            jpql += " and p.permName like CONCAT('%', '"+permission.getPermName()+"','%')";
        }
        if (permission.getActive() != null) {
            jpql += " and p.active = "+permission.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        Long count = (Long) query.getSingleResult();
        return count.intValue();
	}

	@Override
	public void deleteAllPermissions(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.deletePermission(id);
        }
	}

	@Override
	public Boolean deletePermission(Long id) throws Exception{
        dao.deletePermission(id);
        return true;
	}

	@Override
	public PermissionBean findPermissionById(Long id) throws Exception{
        return dao.findPermissionById(id);
	}

	@Override
	public PermissionBean findPermissionByPermName(String permName) throws Exception{
        return dao.findPermissionByPermName(permName);
	}

	@Override
	public List<PermissionBean> listActivePermissions() throws Exception{
        return dao.listActivePermissions();
	}

	@Override
	public List<PermissionBean> listAllPermissions() throws Exception{
        return dao.listAllPermissions();
	}

	@Override
	public List<PermissionBean> searchPermissionsByFields(PermissionBean permission) throws Exception{
        String jpql = "from PermissionBean p where 1=1 ";
        if (permission.getPermName() != null) {
            jpql += " and p.permName like CONCAT('%', '"+permission.getPermName()+"','%')";
        }
        if (permission.getActive() != null) {
            jpql += " and p.active = "+permission.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        List<PermissionBean> results = query.getResultList();
        return results;
	}

	@Override
	public List<PermissionBean> searchPermissionsByFieldsByPage(PermissionBean permission,Integer pagesize,Integer pagenum) throws Exception{
        Integer start = (pagenum-1)*pagesize;
        Integer limit = pagesize;
        String jpql = "from PermissionBean p where 1=1 ";
        if (permission.getPermName() != null) {
            jpql += " and p.permName like CONCAT('%', '"+permission.getPermName()+"','%')";
        }
        if (permission.getActive() != null) {
            jpql += " and p.active = "+permission.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        query.setFirstResult(start); // 设置起始位置
        query.setMaxResults(limit); // 设置返回结果数量
        List<PermissionBean> results = query.getResultList();
        return results;
	}

	public void setDao(PermissionDao dao){
		this.dao = dao;
	}

	@Override
	public void softDeleteAllPermissions(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.softDeletePermission(id);
        }
	}

	@Override
	public boolean softDeletePermission(Long id) throws Exception{
        dao.softDeletePermission(id);
        return true;
	}

	@Override
	public Boolean toggleOnePermission(Long id) throws Exception{
        PermissionBean permission = dao.findPermissionById(id);
        if (permission.getActive()==false) {
            dao.togglePermission(id);
        }
        else {
            Integer count = dao.countActivePermissionRecords();
            if (count > 1){
                dao.togglePermission(id);
            }
        }
        return true;
	}

	@Override
	public Boolean togglePermission(Long id) throws Exception{
        dao.togglePermission(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean updatePermission(PermissionBean permission) throws Exception{
        entityManager.merge(permission);
        return true;
	}

}
